<template>

	<view class="pageContent" :style="{height: pageConfig.scrollHeight}" style="overflow: hidden;">
		<z-paging ref="paging" v-model="tableData" :auto="false" @query="getTableDataFun" :fixed="false"
			use-virtual-list auto-show-back-to-top :back-to-top-style="{ 'opacity':0.6 }" :topZIndex="99999"
			:bottomZIndex="999999">

			<template #top>
				<u-navbar title="审批待办" style="z-index: 99;" left-icon=" " :fixed="false" :safeAreaInsetTop="true">
					<view class="u-nav-slot" slot="right">
						<m-capsule :closeCurrent="1"></m-capsule>
					</view>
				</u-navbar>

				<view class="search x-bc">
					<u-search placeholder="请输入关键字" v-model="searchKey" shape="square" @search="$refs.paging.reload()"
						:animation="false" :actionStyle="{color:'#fff'}" @clear="refreshPage">
						<template #action>
							<view class="x-c">
								<u-icon v-if="!$utils.isPda()" name="scan" color="#fff" size="30"
									@click="searchScanBtn"></u-icon>
							</view>
						</template>
					</u-search>
				</view>

				<z-tabs ref="tabs" unit="px" scroll-count="3" active-color="#51d0d0" :list="tabList" :current="current"
					@change="tabsChange">

					<template #right>
						<view class="x-ec">


							<view class="x-c" style="padding: 0 10px;border-left: 1px solid #e8e8e8;font-size: 12px;"
								v-if="!source">

								<view class="f-dc" style="min-width: 36px;zoom: 0.6;">
									<text>自动</text>
									<text>下一个</text>
								</view>

								<switch :checked="approveWaitToOpenNext" @change="switchChange" color="#1cd842"
									style="zoom: 0.6;"></switch>
							</view>


							<m-dropdown-menu class="drag" ref="filterMenu" marginTop="10" zIndex="9999">
								<template #default="{element}">
									<view class="x-c" style="width: 50px;border-left: 1px solid #e8e8e8;">
										<uni-icons fontFamily="CustomFontPlatform" color="#818181"
											:size="20">{{$utils.toUniCode('&#xe6cb;')}}</uni-icons>
									</view>
								</template>

								<template #Card>
									<view style="min-height: 200px;background-color: #fff;">
										<m-date-time pickerType="module" :InitData="DropDowmMenu_Date"
											@DateSubmit="DateSubmit($event)">
										</m-date-time>

									</view>
								</template>
							</m-dropdown-menu>

						</view>
					</template>
				</z-tabs>
			</template>

			<!-- <view style="padding: 10px;"> -->

			<template #cell="{item,index}">
				<view class="CardBox" style="margin: 10px;"
					:style="{ boxShadow: isActive ? '0 4rpx 12rpx rgba(81, 208, 208, 0.3)' : '0 2rpx 8rpx rgba(0,0,0,0.05)' }"
					@click="openListInfo(item)">
					<view class="CardBox-top">
						<view class="CardBox-top_left">
							<view class="CardBox-top_left_ordinal">
								{{index+1}}
							</view>

							<view class="CardBox-top_left_title">
								<text>{{item.MSGContent}}</text>
							</view>
						</view>

						<!-- <view class="CardBox-top_right">
							<view class="CardBox-top_right_title">
								{{$utils.dateFormat(item.SendDate,'Y-MM-dd hh:mm:ss')}}
							</view>
						</view> -->
					</view>

					<view class="CardBox_content">
						{{item.MSGSubject}}


					</view>

					<view class="CardBox_bottom">
						<view class="CardBox_bottom_right">
							<view class="CardBox_bottom_right_title">
								{{$utils.dateFormat(item.SendDate,'Y-MM-dd hh:mm:ss')}}
							</view>
						</view>

						<view>发起人：{{item.Sender}}</view>
					</view>
				</view>

			</template>

			<!-- </view> -->
		</z-paging>

		<m-pda-scancode v-if="$utils.isPda()" listenName="ApproveScanCode"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>

	</view>
</template>

<script>
	// import swiperListItem from '@/components/swiper-list-item/swiper-list-item';
	export default {
		// components: {
		// 	swiperListItem
		// },
		props: {
			config: {
				type: Object,
				default: () => ({
					tabbarHeight: 0,
					scrollHeight: 500
				})
			},
			isPage: {
				type: Boolean,
				default: () => {
					return true;
				}
			}
		},
		data() {
			return {
				isAlready: false,
				searchKey: '',
				stickShow: false,
				DropDowmMenu_Date: {
					DateTitle: "",
					SDate: "",
					EDate: "",
				},
				tabList: [{
						name: '待我处理',
						badge: {
							count: 0
						},
					},
					{
						name: '我已处理',
						badge: {
							count: 0
						},
					},
					{
						name: '我创建的',
						badge: {
							count: 0
						},
					},
					{
						name: '相关审批',
						badge: {
							count: 0
						},
					},
				],
				current: 0,
				tableData: [],
				tableData_all: [], // 数据集合
				choiceRow: {}, // 记录选中数据
				formMenus: [{
					name: '隐藏表头',
					value: '',
					icon: 'order'
				}, ],
				source: "",
				isActive: false
			};
		},
		onLoad(option) {
			let that = this;
			if (option.source) {
				this.source = option.source;
			}
		},
		created() {
			let that = this;

			// 自定义默认时间
			let SDate = this.$utils.getDateAfterNDays(-10);
			let EDate = this.$utils.getDateAfterNDays(0);
			let data = {
				DateTitle: SDate + "\n" + EDate,
				SDate: SDate,
				EDate: EDate,
			};
			Object.assign(this.DropDowmMenu_Date, data);

			that.getTableDataFun();
		},
		computed: {
			pageConfig() {
				const config = this.$utils.deepClone(this.config);
				if (this.isPage) {
					config.scrollHeight = `100vh`;
				} else {
					config.scrollHeight = `${config.scrollHeight}px`;
				}
				return config;
			},
			approveWaitToOpenNext() { // 获取记录是否允许开启下一个
				return this.$store.state.st_comPageConfig.approveWaitToOpenNext;
			}
		},
		mounted() {
			let that = this;
			// 停止表单审批触发列表刷新，改用页面打开时触发
			// 刷新
			// uni.$on('refreshToApprove', function() {
			// 	that.refreshPage();
			// });

			uni.$on('ApproveScanCode', function(content) {
				that.$utils.showLoading('正在解码');
				that.getMainInfo(content);
			})



			// 用于接收审批待办打开的详情页触发下一条的指令
			uni.$on('switch-to-next-item', function(data) {
				if (that.current == 0 && that.approveWaitToOpenNext) { // 只有待我处理才会触发
					that.getNextItemById();
				}
			})
		},
		onUnload() { // 监听页面卸载,
			uni.$off('ApproveScanCode');
			uni.$off('refreshToApprove');
			uni.$off('switch-to-next-item');
		},
		methods: {
			onMyShow() {
				// 判断是否是第一次打开
				if (this.isAlready) {
					this.refreshPage();
				}
			},
			switchChange(e) {
				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'st_comPageConfig.approveWaitToOpenNext',
					data: e.detail.value,
					StorageName: 'approveWaitToOpenNext',
					StorageData: e.detail.value,
				});
			},
			getNextItemById() {
				let choiceRow = this.$utils.deepClone(this.choiceRow);
				// 找到当前 id 对应的索引
				const currentIndex = this.tableData.findIndex(item => item.AuditID === choiceRow.AuditID);
				let listType = 'next';
				let nextData = [];
				if (currentIndex == -1 || currentIndex == this.tableData.length - 1) {
					// 如果未找到当前 id 的数据，返回 null
					if (currentIndex == -1) {
						listType = 'null';
					}
					if (currentIndex == this.tableData.length - 1) {
						listType = 'lastData';
					};

				} else {
					nextData = this.tableData[currentIndex + 1];
					this.choiceRow = this.$utils.deepClone(nextData);
				}

				let obj = {
					listType: listType,
					nextData: nextData,
				};


				uni.$emit("emitNextItem", obj); // 向详情页发送处理后的数据

			},
			getMainInfo(data) {
				that.searchKey = data;
				that.refreshPage();
			},
			refreshPage() {
				let that = this;
				if (that.$refs.paging) {
					that.$refs.paging.reload();
				}
			},
			DateSubmit(data) { // 选中时间
				this.DropDowmMenu_Date = this.$utils.deepClone(data);
				this.$refs.filterMenu.close();
				this.$refs.paging.reload();
			},
			searchScanBtn() { // 搜索栏扫码
				let that = this;

				/* uni.scanCode({
					success: function(res) {
						that.searchKey = res.result;
						that.refreshPage();
					}
				}); */
				this.$scanPopup.openScan({
					success: (res) => {
						that.searchKey = res.result;
						that.refreshPage();
					}
				})
			},
			openListInfo(data) { // 打开对应单据
				let that = this;
				// 1、记录当前选中数据以及下一条数据，并对数据进行处理
				// 记录选中的数据
				this.choiceRow = data;
				this.isActive = true
				setTimeout(() => {
					that.isActive = false
				}, 200)

				if (data.Url) {

					const queryString = data.Url;
					const params = queryString.split('&').reduce((acc, current) => {
						const [key, value] = current.split('=');
						acc[key] = decodeURIComponent(value); // 解码URL编码的字符  
						return acc;
					}, {});

					if (params.objName == '不合格评审表单' && params.keyName == 'BadReviewID') {
						uni.navigateTo({
							url: '/st_qms/ChoiceIAddnvoices/ReviewPageInfo?id=' + params.keyValue
						})
					} else {
						let returnData = {
							detailTitle: params.objName,
							detailName: params.objName,
							keyName: params.keyName,
							keyValue: params.keyValue,
							dataInfo: {
								titleColName: '',
								showColumnsInfo: [],
								tagColumnsInfo: [],
							}
						}
						console.log(returnData);

						// 模拟测试
						this.$store.commit('ChangeAndSetStateData', {
							Name1: 'MenuDetail',
							data: returnData
						});


						uni.navigateTo({
							url: '/commonPage/Form/Edit' + '?origin=approveWaitList',
						})
					}
				}



			},
			getTableDataFun() { // 获取待办数据
				let that = this;
				this.$utils.showLoading();
				try {
					that.Request.request('APP_MessageToDoRemind', {
						StartTime: that.DropDowmMenu_Date.SDate,
						EndTime: that.DropDowmMenu_Date.EDate,
						searchKey: that.searchKey,
						UserID: that.$store.state.UserInfo.UserID,
						MSGType: 1,
						source: that.source,
					}, (ret) => {
						that.$nextTick(() => {

							that.isAlready = true;
							let data = that.processArray(ret.data);
							that.tableData_all = data;
							that.tabList[0].badge.count = data[0].length;
							that.$refs.paging.setLocalPaging(data[that.current]);
							that.$utils.hideLoading();
						})

					}, (err) => {
						that.$refs.paging.setLocalPaging(false);
						that.$utils.hideLoading();
					})

				} catch (error) {
					that.$refs.paging.setLocalPaging(false);
					that.$utils.hideLoading();
				}
			},
			processArray(input) {
				// 将输入对象转换为一个数组，只包含值
				return Object.values(input).map(item => {
					// 确保每个元素都是数组，如果不是，则转换（在这个特定情况下，所有值已经是数组或空）
					// if (!Array.isArray(item)) {
					// 	return [item]; // 如果不是数组，则将其包装成数组
					// }

					if (this.$utils.isEmpty(item)) {
						return []
					}
					return item; // 如果是数组，则直接返回
				});
			},

			// tabs切换
			tabsChange(index) {
				this.current = index;
				this.$refs.filterMenu.close();
				// 将滚动条跳转到顶部
				this.$refs.paging.scrollToTop(false);
				// this.$refs.paging.setLocalPaging(this.tableData_all[this.current]);
				this.$refs.paging.reload();
			},

			// 退出当前页面
			CloseShopPage() {
				uni.navigateBack({
					delta: 999
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	$h-padding: 5px;
	$v-padding: 10px;
	$radius: 5px;

	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	.pageContent {
		background-color: #f2f1f6;
	}


	.MenuSelect {
		display: flex;
		align-items: center;
		margin-left: 8px;
		padding: 0 10px;
		height: 35px;
		font-size: 16px;
		font-weight: 500;
		background-color: rgba(0, 0, 0, .03) !important;
		border-radius: $radius;

		.text {
			font-size: 14px;
			margin-right: 5px
		}
	}

	.search {
		background-color: #fff;
		background-color: #51d0d0;
		padding: 6px 10px;

		.scanQrCode {
			width: 20rpx;
			padding: 5rpx;
		}

		.MenuText {
			font-size: 14px;
			border-right: 1px solid #999;
			padding-right: 10px;
			margin-right: 4px;
		}
	}

	.MenuBoxMax {
		position: relative;
		height: 42px;
		width: 100%;
		border-bottom: 4px solid #f2f2f2;

		.MenuBox {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			background-color: #fff;

			.selectSearchDom {
				padding-right: 10rpx;
			}
		}
	}

	.CardBox {
		position: relative;
		border-radius: 16rpx;
		padding: 24rpx;
		background: #ffffff;
		transition: all 0.2s ease;
		margin-bottom: 20rpx;

		/* 新增激活状态 */
		&:active {
			transform: scale(0.98);
			background: #f8fdff;
		}

		&-top {
			display: flex;
			align-items: flex-start;
			justify-content: space-between;
			margin-bottom: 16rpx;

			&_left {
				display: flex;
				align-items: flex-start;
				gap: 12rpx;

				/* 序号样式优化 */
				&_ordinal {
					flex-shrink: 0;
					background: linear-gradient(135deg, #51d0d0, #2ab5b5);
					color: #fff;
					font-size: 24rpx;
					padding: 4rpx 12rpx;
					border-radius: 8rpx;
					line-height: 1.4;
				}

				/* 标题容器 */
				&_title {
					flex: 1;
					min-width: 0;

					text {
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
						font-size: 32rpx;
						color: #333;
						line-height: 1.4;
					}
				}
			}

			&_right {
				flex-shrink: 0;

				&_title {
					font-size: 24rpx;
					color: #999;
					padding: 4rpx 12rpx;
					background: #f5f5f5;
					border-radius: 8rpx;
					white-space: nowrap;
				}
			}
		}

		&_content {
			font-size: 28rpx;
			color: #666;
			line-height: 1.6;
			margin: 16rpx 0;
			min-height: 80rpx;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 3;
			overflow: hidden;
			position: relative;

			/* 添加渐变遮罩 */
			// &::after {
			// 	content: '';
			// 	position: absolute;
			// 	bottom: 0;
			// 	left: 0;
			// 	right: 0;
			// 	height: 40rpx;
			// 	background: linear-gradient(to bottom, rgba(255, 255, 255, 0), #fff 80%);
			// 	pointer-events: none;
			// }
		}

		&_bottom {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 24rpx;
			color: #999;
			padding-top: 16rpx;
			border-top: 1rpx solid #eee;

			&_right {
				flex-shrink: 0;

				&_title {
					font-size: 24rpx;
					color: #999;
					padding: 4rpx 12rpx;
					// background: #f5f5f5;
					border-radius: 8rpx;
					white-space: nowrap;
				}
			}
		}
	}
</style>